package view.dialog;

import dao.CommodityDAO;
import dao.CategoryDAO;
import tool.DisableEditTableModel;

import javax.swing.*;

import bean.Category;

import java.awt.*;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Objects;
import java.util.Vector;

public class CategoryDialog extends JDialog {
    private static final long serialVersionUID = -8588701144979413128L;
    private CategoryDAO categoryDAO;
    private CommodityDAO commodityDAO;
    private Dimension dimension;
    private JPanel contentPane;
    private JScrollPane scrollPane;
    private JTable table;
    private DisableEditTableModel tableModel;
    private Vector<String> columnNames;
    private JPanel rightPanel;
    private JPanel panel1, panel2, panel3, panel4, panel5, panel6;
    private JButton editCategoryButton;
    private JButton addCategoryButton;
    private JButton deleteCategoryButton;
    private JTextField categoryIdTextField;
    private JTextField categoryNameTextField;
    private JButton refreshButton;
    private JButton submitButton;

    public CategoryDialog(Connection conn) throws SQLException, ClassNotFoundException {
        categoryDAO = new CategoryDAO(conn);
        commodityDAO = new CommodityDAO(conn);
        setSize(450, 300);
        setTitle("管理商品类别");
        setLocationRelativeTo(null);
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        setModalityType(ModalityType.APPLICATION_MODAL);
        dimension = new Dimension(83, 22);
        contentPane = (JPanel) getContentPane();
        contentPane.setLayout(new BorderLayout());
        scrollPane = new JScrollPane();
        table = new JTable();
        tableModel = new DisableEditTableModel();
        columnNames = new Vector<>();
        columnNames.addElement("商品类别编号");
        columnNames.addElement("商品类别名称");
        tableModel.setDataVector(rowsData(), columnNames);
        table.setModel(tableModel);
        scrollPane.setViewportView(table);
        contentPane.add(scrollPane, BorderLayout.CENTER);
        contentPane.add(new JPanel(new GridLayout(6, 1)), BorderLayout.EAST);
        rightPanel = (JPanel) contentPane.getComponent(1);
        rightPanel.add(new JPanel());
        panel1 = (JPanel) rightPanel.getComponent(0);
        editCategoryButton = new JButton("编辑商品类别");
        editCategoryButton.addActionListener(actionEvent -> {
            int length = table.getSelectedRows().length;
            if (length == 1) {
                int categoryId = (int) tableModel.getValueAt(table.getSelectedRow(), 0);
                try {
                    Category category = categoryDAO.selectById(categoryId);
                    categoryIdTextField.setText(String.valueOf(category.getCategoryId()));
                    categoryNameTextField.setText(category.getCategoryName());
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        });
        panel1.add(editCategoryButton);
        rightPanel.add(new JPanel());
        panel2 = (JPanel) rightPanel.getComponent(1);
        addCategoryButton = new JButton("添加商品类别");
        addCategoryButton.addActionListener(actionEvent -> {
            table.clearSelection();
            categoryIdTextField.setText(null);
            categoryNameTextField.setText(null);
        });
        panel2.add(addCategoryButton);
        rightPanel.add(new JPanel());
        panel3 = (JPanel) rightPanel.getComponent(2);
        deleteCategoryButton = new JButton("删除商品类别");
        deleteCategoryButton.addActionListener(actionEvent -> {
            int[] rows = table.getSelectedRows();
            if (rows.length > 0) {
                for (int rowIndex = rows.length - 1; rowIndex > -1; rowIndex--) {
                    int categoryId = (int) tableModel.getValueAt(rows[rowIndex], 0);
                    try {
                        int count = commodityDAO.selectIdCountByCategoryId(categoryId);
                        if (count == 0) {
                            categoryDAO.delete(categoryId);
                            tableModel.setDataVector(rowsData(), columnNames);
                        } else if (count == -1) {
                            JOptionPane.showMessageDialog(null, "商品类别编号不能为0");
                            break;
                        } else {
                            JOptionPane.showMessageDialog(null, "商品类别编号：" + categoryId + "包含有商品");
                            break;
                        }
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        panel3.add(deleteCategoryButton);
        rightPanel.add(new JPanel());
        panel4 = (JPanel) rightPanel.getComponent(3);
        panel4.add(new JLabel("商品类别编号"));
        categoryIdTextField = new JTextField();
        categoryIdTextField.setPreferredSize(dimension);
        categoryIdTextField.setEnabled(false);
        panel4.add(categoryIdTextField);
        rightPanel.add(new JPanel());
        panel5 = (JPanel) rightPanel.getComponent(4);
        panel5.add(new JLabel("商品类别名称"));
        categoryNameTextField = new JTextField();
        categoryNameTextField.setPreferredSize(dimension);
        panel5.add(categoryNameTextField);
        rightPanel.add(new JPanel());
        panel6 = (JPanel) rightPanel.getComponent(5);
        refreshButton = new JButton("刷新");
        refreshButton.addActionListener(actionEvent -> {
            try {
                tableModel.setDataVector(rowsData(), columnNames);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        });
        panel6.add(refreshButton);
        submitButton = new JButton("提交");
        submitButton.addActionListener(actionEvent -> {
            String categoryName = categoryNameTextField.getText();
            boolean state;
            if (Objects.nonNull(categoryName) && categoryName.length() > 0) {
                try {
                    if (Objects.nonNull(categoryDAO.selectByName(categoryName))) {
                        JOptionPane.showMessageDialog(null, "指定商品类别名称已存在，请重新编辑商品类别名称");
                        categoryNameTextField.requestFocusInWindow();
                        categoryNameTextField.selectAll();
                    } else {
                        String categoryIdText = categoryIdTextField.getText();
                        // 编辑商品类别
                        if (Objects.nonNull(categoryIdText) && categoryIdText.length() > 0) {
                            int categoryId = Integer.parseInt(categoryIdText);
                            state = categoryDAO.update(categoryId, categoryName);
                            if (state) {
                                JOptionPane.showMessageDialog(null, "编辑商品类别成功");
                                categoryIdTextField.setText(null);
                                categoryNameTextField.setText(null);
                            } else
                                JOptionPane.showMessageDialog(null, "编辑商品类别失败");
                          // 添加商品类别
                        } else {
                            state = categoryDAO.insert(categoryName);
                            if (state) {
                                JOptionPane.showMessageDialog(null, "添加商品类别成功");
                                categoryIdTextField.setText(null);
                                categoryNameTextField.setText(null);
                            } else
                                JOptionPane.showMessageDialog(null, "添加商品类别失败");
                        }
                        tableModel.setDataVector(rowsData(), columnNames);
                    }
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            } else
                JOptionPane.showMessageDialog(null, "商品类别名称不能为空");
        });
        panel6.add(submitButton);
    }

    private Vector<Vector<Object>> rowsData() throws SQLException {
        Vector<Vector<Object>> rowsData = new Vector<>();
        Vector<Category> categories = categoryDAO.selectAll();
        for (Category category : categories) {
            Vector<Object> rowData = new Vector<>();
            rowData.addElement(category.getCategoryId());
            rowData.addElement(category.getCategoryName());
            rowsData.addElement(rowData);
        }
        return rowsData;
    }
}
